package com.fysports.web.handler;

import com.jfinal.handler.Handler;
import com.jfinal.log.Log;
import com.fysports.framework.render.MainRenderFactory;
import com.fysports.web.config.asyn.ThreadSystemLog;
import com.fysports.web.kit.commons.*;
import com.fysports.web.model.system.SystemLog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 记录全局日志
 * Created by konbluesky
 * Date : 14-9-11 下午6:06
 * Project : JdmData_WebServer
 */
public class SystemLogHandler extends Handler {
    private static Log log = Log.getLog(SystemLogHandler.class);

    public static String reqSystemLogKey = "reqSystemLog";

    private String[] excludes = { "/css", "/js", "/img", "/plugin/assets" };


    @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response,
            boolean[] isHandled) {
        //排除不满足规则url
        if (StringKit.containVal(excludes, target)) {
            next.handle(target, request, response, isHandled);
            return;
        }

        log.debug("初始化访问系统功能日志");
        SystemLog reqSystemLog = getSystemLog(request);
        long starttime = DateTimeKit.getDateByTime();
        reqSystemLog.set("startdate", DateTimeKit.getSqlTimestamp(starttime));//开始时间
        reqSystemLog.set("starttime", starttime);//开始时间
        request.setAttribute(reqSystemLogKey, reqSystemLog);    //此处放入request，方便拦截器或者其他地方中获取

        log.debug("设置Header");
        request.setAttribute("decorator", "none");
        response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
        response.setHeader("Pragma", "no-cache"); //HTTP 1.0
        response.setDateHeader("Expires", 0); //prevents caching at the proxy server

        next.handle(target, request, response, isHandled);

        log.debug("请求处理完毕，计算耗时");

        // 结束时间
        long endtime = DateTimeKit.getDateByTime();
        reqSystemLog.set("enddate", DateTimeKit.getSqlTimestamp(endtime));
        reqSystemLog.set("endtime", endtime);

        // 总耗时
        Long haoshi = endtime - starttime;
        reqSystemLog.set("haoshi", haoshi);

        // 视图耗时
        Long renderTime = 0L;
        if (null != request.getAttribute(MainRenderFactory.renderTimeKey)) {
            renderTime = (Long) request.getAttribute(MainRenderFactory.renderTimeKey);
        }
        reqSystemLog.set("viewhaoshi", renderTime);

        // 视图渲染结果
        //0: ftl-渲染失败; 1: ftl-渲染成功;
        //2: json-渲染失败;3: json-渲染成功;
        String renderFlag = "0";
        if (null != request.getAttribute(MainRenderFactory.renderFlag)) {
            renderFlag = (String) request.getAttribute(MainRenderFactory.renderFlag);
        }
        reqSystemLog.set("status", renderFlag);

        // action耗时
        reqSystemLog.set("actionhaoshi", haoshi - renderTime);

        log.debug("日志添加到入库队列");
        ThreadSystemLog.add(reqSystemLog);
    }


    /**
     * 创建日志对象,并初始化一些属性值
     *
     * @param request
     * @return
     */
    public SystemLog getSystemLog(HttpServletRequest request) {
        String requestPath = WebContextKit.getRequestURIWithParam(request);
        String ip = IPAddressKit.getIpAddr(request);
        String referer = request.getHeader("Referer");
        String userAgent = request.getHeader("User-Agent");
        String cookie = request.getHeader("Cookie");
        String method = request.getMethod();
        String xRequestedWith = request.getHeader("X-Requested-With");
        String host = request.getHeader("Host");
        String acceptLanguage = request.getHeader("Accept-Language");
        String acceptEncoding = request.getHeader("Accept-Encoding");
        String accept = request.getHeader("Accept");
        String connection = request.getHeader("Connection");

        String useruid = CookiesKit.getSystemUserUUID(request);
        SystemLog reqSystemLog = new SystemLog();

        reqSystemLog.set("useruuid", useruid);
        reqSystemLog.set("ips", ip);
        reqSystemLog.set("requestpath", requestPath);
        reqSystemLog.set("referer", referer);
        reqSystemLog.set("useragent", userAgent);
        reqSystemLog.set("cookie", cookie);
        reqSystemLog.set("method", method);
        reqSystemLog.set("xrequestedwith", xRequestedWith);
        reqSystemLog.set("host", host);
        reqSystemLog.set("acceptlanguage", acceptLanguage);
        reqSystemLog.set("acceptencoding", acceptEncoding);
        reqSystemLog.set("accept", accept);
        reqSystemLog.set("connection", connection);

        return reqSystemLog;
    }

}
